<template>
  <myHeader></myHeader>
  <div class="mock-main">
    <div class="content">
      <div class="xc active">
        <ul class="tab">
          <template v-for="(item, index) in navData[navIndex].children" :key="index">
            <li :class="index == navInd ? 'active' : ''"><router-link :to="`/${navData[navIndex].url}/${item.id}`">{{
                item.name }}</router-link></li>
          </template>
        </ul>
        <div class="cont">
          <div class="active">
            <ul class="t">
              <li>
                <img class="homeZgzMnksICon" src="../assets/img/homeZgzMnksICon.png">
                <a @click="jumpFn({ url: `/${route.params.type}/${route.params.subject}/exam`, type: 'exam' })">
                  <div>
                    <img src="../assets/img/km1-img5.png" alt="">
                  </div>
                  <p>模拟考试</p>
                  <p>模拟在线真实考场</p>
                </a>
                <img class="vip" src="../assets/img/subject-vip.png" alt="" v-show="subjectVipData.examCharged">
              </li>
              <li>
                <img class="homeZgzMnksICon" src="../assets/img/homeZgzMnksICon.png">
                <a @click="jumpFn({ url: `/${route.params.type}/${route.params.subject}/selected`, type: 'selected' })">
                  <div>
                    <img src="../assets/img/km1-img1.png" alt="">
                  </div>
                  <p>精选练习</p>
                  <p>快速掌握考试难点</p>
                </a>
                <img class="vip" src="../assets/img/subject-vip.png" alt="" v-show="subjectVipData.selectedCharged">
              </li>
            </ul>
            <ul class="b">
              <li>
                <a @click="jumpFn({ url: `/${route.params.type}/${route.params.subject}/all`, type: 'all' })">
                  <div>
                    <img src="../assets/img/km1-img6.png" alt="">
                  </div>
                  <p>全部习题</p>
                  <p>按顺序练习做题</p>
                </a>
                <img class="vip" src="../assets/img/subject-vip.png" alt="" v-show="subjectVipData.allCharged">
              </li>
              <li>
                <a @click="jumpFn({ url: `/${route.params.type}/${route.params.subject}/chapter`, type: 'chapter' })">
                  <div>
                    <img src="../assets/img/km1-img2.png" alt="">
                  </div>
                  <p>章节练习</p>
                  <p>按照法规章节逐步分类</p>
                </a>
                <img class="vip" src="../assets/img/subject-vip.png" alt="" v-show="subjectVipData.allCharged">
              </li>
              <li v-if="route.params.subject == 110528 || route.params.subject == 110529">
                <a href="javascript:;" @click="groupingFn">
                  <div>
                    <img src="../assets/img/km1-img9.png" alt="">
                  </div>
                  <p>分组练习</p>
                  <p>分门别类重点突破</p>
                </a>
                <img class="vip" src="../assets/img/subject-vip.png" alt="" v-show="subjectVipData.groupCharged">
              </li>
              <li class="wrong">
                <a @click="jumpFn({ url: `/${route.params.type}/${route.params.subject}/wrong`, type: 'wrong' })">
                  <div>
                    <img src="../assets/img/km1-img4.png" alt="">
                  </div>
                  <p>错题本</p>
                  <p>全部错题（<i>{{ errorNum }}</i>题）</p>
                </a>
              </li>
            </ul>
            <div class="note">
              {{ year }}<span class="title">{{ navData[navIndex].children[navInd].name }}</span>考试形式为上机考试，<span class="num">{{ examNumSum || 0 }}</span>道题，考试时间<span class="time">{{ isNaN(examSetting.duration) ? 0 : examSetting.duration / 60 }}</span>分钟，满分{{ examSetting.fullScore || 0 }}分，<span
                class="pass">{{ examSetting.passScore || 0 }}</span>分合格。
            </div>
            <div class="clear">
              <button class="clear-btn" :disabled="clearDisabled" @click="clearExercisesRecordFn">清除练习记录</button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import myHeader from '@/components/header.component.vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { ref, watch, getCurrentInstance } from 'vue';
const { $api } = getCurrentInstance().appContext.config.globalProperties;
import { useRoute, useRouter } from 'vue-router';
const route = useRoute()
const router = useRouter()
import { useNavStore } from '@/stores/nav.store.js';
const navStore = useNavStore()
const navData = ref(navStore.listData || [])
const navIndex = ref(0)
const navInd = ref(0)
const isToken = ref(localStorage.getItem('token') ? true : false)
const errorNum = ref(0)
const year = ref(new Date().getFullYear())
const examSetting = ref({})
const examNumSum = ref()
const clearDisabled = ref(false)
const subjectVipData = ref({})
const menuAuthData = ref({})

// 没有一级科目重定向
if (!route.params.type) {
  router.replace(`/${navData.value[0].url}/${navData.value[0].children[0].id}`)
}
// 没有二级科目重定向
else if (!route.params.subject) {
  let _type = navData.value.filter(x => x.url === route.params.type);
  router.replace(`/${_type[0].url}/${_type[0].children[0].id}`)
}
// 设置导航下标
const setNavIndexIndFn = () => {
  navData.value.forEach((item, index) => {
    if (item.url === route.params.type) {
      navIndex.value = index;
    }
    if (route.params.subject) {
      item.children.forEach((ite, ind) => {
        if (ite.id === Number(route.params.subject)) {
          navInd.value = ind;
        }
      })
    }
  })
}
setNavIndexIndFn()
// 监听
watch([() => route.params], (val) => {
  // 设置导航下标
  if (val[0].type && val[0].subject) {
    setNavIndexIndFn()
    getExamCountFn()
    getSubjectExamConfig()
  }
  // 监听是否登录
  isToken.value = localStorage.getItem('token') ? true : false;
})
// 获取习题数量
const getExamCountFn = () => {
  $api.exerciseGetCountApi({
    subjectId: route.params.subject
  }).then((res) => {
    if (res.errno === 0) {
      errorNum.value = res.result.wrong;
      return false;
    }
    ElMessage.error(res.errmsg)
  })
}
// 获取科目考试配置
const getSubjectExamConfig = () => {
  if (isToken.value) {
    $api.getSubjectApi({
      subjectId: route.params.subject
    }).then((res) => {
      if (res.errno === 0) {
        if (res.result && res.result.examSetting) {
          let _examSetting = res.result.examSetting;
          examSetting.value = _examSetting;
          examNumSum.value = _examSetting.radioSize + _examSetting.checkboxSize + _examSetting.judgeSize;
          getMenuAuthFn()
          // 获取哪些科目是VIP
          $api.getExerciseVipStrategyApi({
            subjectId: route.params.subject
          }).then((res) => {
            if (res.errno === 0) {
              if (res.result) {
                subjectVipData.value = res.result;
              }
              return false;
            }
            ElMessage.error(res.errmsg)
          })
        } else {
          ElMessageBox.confirm('当前科目习题未开设', '系统提示', {
            showClose: false,
            showCancelButton: false,
            confirmButtonText: '我已知晓'
          }).catch(() => { })
        }
        return false;
      }
      ElMessage.error(res.errmsg)
    })
  }
}
if (route.params.subject) {
  getExamCountFn()
  getSubjectExamConfig()
}
// 栏目是否有权限
const getMenuAuthFn = () => {
  $api.checkExerciseVipAuthApi({
    subjectId: route.params.subject
  }).then((res) => {
    if (res.errno === 0) {
      menuAuthData.value = res.result;
      return false;
    }
    ElMessage.error(res.errmsg)
  })
}
// 跳转
const jumpFn = (val) => {
  // 是否登录
  if (isToken.value) {
    if (val.type === 'exam' && !menuAuthData.value.examChargedAuth) {
      router.push(`/${route.params.type}/${route.params.subject}/pay`)
      return false;
    }
    if ((val.type === 'all' || val.type === 'chapter') && !menuAuthData.value.allExerciseAuth) {
      router.push(`/${route.params.type}/${route.params.subject}/pay`)
      return false;
    }
    if (val.type === 'selected' && !menuAuthData.value.selectedExerciseAuth) {
      router.push(`/${route.params.type}/${route.params.subject}/pay`)
      return false;
    }
    if (Object.keys(examSetting.value).length > 0) {
      if (val.type === 'wrong' && errorNum.value < 1) {
        ElMessageBox.confirm('错题本暂无数据', '系统提示', {
          showClose: false,
          showCancelButton: false,
          confirmButtonText: '我已知晓'
        }).catch(() => {})
        return false;
      }
      localStorage.setItem('analysisChargedAuth', menuAuthData.value.analysisChargedAuth)
      localStorage.setItem('examSetting', JSON.stringify(examSetting.value))
      router.push(val.url)
    } else {
      ElMessageBox.confirm('当前科目习题未开设', '系统提示', {
        showClose: false,
        showCancelButton: false,
        confirmButtonText: '我已知晓'
      }).catch(() => { })
    }
  } else {
    router.replace('/login')
  }
}
// 清除习题记录
const clearExercisesRecordFn = () => {
  if (isToken.value) {
    clearDisabled.value = true;
    $api.clearExerciseRecordApi({id: 123}).then((res) => {
      setTimeout(() => {
        clearDisabled.value = false;
      }, 1000)
      if (res.errno === 0) {
        ElMessage.success('清除成功')
        errorNum.value = 0;
        return false;
      }
      ElMessage.error(res.errmsg)
    })
  } else {
    ElMessage.warning('请先登录')
  }
}
// 分组练习提示
const groupingFn = () => {
  ElMessageBox.confirm('分组练习正在开发中...', '系统提示', {
    showClose: false,
    showCancelButton: false,
    confirmButtonText: '我已知晓'
  }).then(() => {}).catch(() => {})
}
</script>

<style lang="scss" scoped>
@import '../assets/css/mock.css';

.mock-main .cont .t li a {
  display: block;
  width: 100%;
  height: 100%;
  cursor: pointer;
}

.clear {
  text-align: center;

  &-btn {
    background: transparent;
    font-size: 14px;
  }
}
</style>